package com.dhruvtaara.beta.action;

import com.dhruvtaara.beta.model.persistance.Datastore;
import com.dhruvtaara.beta.toolset.DefaultEncryption;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class LoginAction {
	
	/**
	 * 
	 * @param emailId
	 * @param password
	 * @return
	 */
	public boolean doLogin(
			String emailId, 
			String password){		
		return validateCredentials(emailId, password);
	}

	/**
	 * 
	 * @param emailId
	 * @param password
	 * @return
	 */
	public boolean validateCredentials(String emailId, String password) {
		DatastoreService datastore = Datastore.get();
		
		boolean isValid = true;
		
		Query userQuery = new Query("User");
		userQuery.addFilter("emailAddress", Query.FilterOperator.EQUAL, emailId);
		userQuery.addFilter("password", Query.FilterOperator.EQUAL, DefaultEncryption.encrypt(password));
		
		PreparedQuery query = datastore.prepare(userQuery);
		
		Entity user = query.asSingleEntity();
		
		if(user == null){
			isValid = false;
		}
		return isValid;
	}
}
